package com.example.blog.util.PcUtils;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

@Controller
@RequestMapping("/files")
public class FileShowUtils {

    @GetMapping("/{fileName}")
    public void showFile(@PathVariable("fileName") String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        File avatarFile = UploadFileUtils.getFile(request,fileName);
        // 检查文件是否存在
        if (!avatarFile.exists()) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        // 设置响应内容类型为图片
        response.setContentType(request.getServletContext().getMimeType(avatarFile.getName()));

        // 获取输出流
        OutputStream outputStream = response.getOutputStream();

        try (FileInputStream fileInputStream = new FileInputStream(avatarFile)) {
            // 将头像文件的内容写入响应输出流
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }
        // 关闭输出流
        outputStream.close();
    }
}
